<?php

class User_like {
    /*
     * 数据表名
     */
    const TABLE_NAME = 'user_like';
    /*
     * redis命名空间
     */
    const REDIS_NAME = 'userLike';

    /**
     * 缓存实例
     *
     * @var Helper_Cache_Memcache
     */
    protected $_cacheInstance;
    /**
     * redis实例
     *
     * @var Helper_Cache_Memcache
     */
    protected $_redisInstance;
    /**
     * db实例
     *
     * @var Helper_Cache_Memcache
     */
    protected $_dbInstance;
    /**
     * 单例对象
     */
    public static $singletonObjects;

    /**
     * 获取单例
     */
    public static function getInstance() {
        $className = __CLASS__;
        if (!isset(self::$singletonObjects[$className])) {
            self::$singletonObjects[$className] = new self();
        }

        return self::$singletonObjects[$className];
    }

    /**
     * 构造器
     *
     * @param int $uId
     */
    protected function __construct() {

//        $this->_cacheInstance = $this->_getCache();
        $this->_dbInstance = $this->_getMysql();
        $this->_redisInstance = $this->_getRedis();
    }

    /*
     * 获取cache实例
     */

    public function _getCache() {

        return Common::getCache();
    }

    /*
     * 获取redis实例
     */

    public function _getRedis() {
//        $config = array ('current'=>'127.0.0.1' , 'old' =>'6380') ;
//        $redis = new Helper_Redis($config);
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6380);
        return $redis;
    }

    /*
     * 获取db实例
     */

    public function _getMysql() {

        return Common::getMysql();
    }

    /*
     * 验证PId UId 是否有记录
     */

    public function checkUIdPId($pid) {

        $table = self::TABLE_NAME;
        $where = array('UId' => $_SESSION['UId'], 'PId' => $pid);
        return $this->_dbInstance->get($table, $where);
    }

    /**
     * 根据产品id记录用户喜好
     * user_like表
     */
    public function insertUserLike($value) {

        $table = self::TABLE_NAME;
        $this->_dbInstance->add($table, $value);
    }

    /*
     * 更新用户喜好表
     */

    public function updateUserLike($value, $pid) {

        $table = self::TABLE_NAME;
        $where = array('UId' => $_SESSION['UId'], 'PId' => $pid);
        $this->_dbInstance->update($table, $where, $value);
    }
    /**
     * 获取查询所对应的维度
     * @param type $pid
     * @return int 
     */
    public function getValue($pid) {

        /*
         * 产品信息
         */

        $productinfo = Product_Info::getInstance()->getProuctInfoByPId($pid);

        /**
         * 产品消费层次
         */
        $levels = Product_Levels::getInstance()->getLevelsId($pid);

        /**
         * 产品消费年龄段
         */
        $age = Product_Age::getInstance()->getAgeId($pid);

        /**
         * 产品消费性别
         */
        $sex = Product_Sex::getInstance()->getSexId($pid);

        $arrlevels = array();
        if ($levels) {
            foreach ($levels as $key => $value) {
                if ($value['DId'] == 3) {
                    $arrlevels['DHihgLevels'] = 1;
                }
                if ($value['DId'] == 4) {
                    $arrlevels['DMiddleLevels'] = 1;
                }
                if ($value['DId'] == 5) {
                    $arrlevels['DLowLevels'] = 1;
                }
            }
        }
        if ($age) {
            foreach ($age as $key => $value) {
                if ($value['DId'] == 6) {
                    $arrlevels['DOldAge'] = 1;
                }
                if ($value['DId'] == 7) {
                    $arrlevels['DYouthAge'] = 1;
                }
                if ($value['DId'] == 8) {
                    $arrlevels['DInfancyAge'] = 1;
                }
            }
        }
        if ($sex) {
            foreach ($sex as $key => $value) {
                if ($value['DId'] == 1) {
                    $arrlevels['DManSex'] = 1;
                }
                if ($value['DId'] == 2) {
                    $arrlevels['DWomanSex'] = 1;
                }
            }
        }

        $arrlevels['PBrand'][$productinfo['PBrand']] = 1;
        $arrlevels['BCat'][$productinfo['BCat']] = 1;
        $arrlevels['SCat'][$productinfo['SCat']] = 1;

        return $arrlevels;
    }

    /**
     * 记录用户喜好到redis
     * @param type $value 
     */
    public function saveToRedis($pid) {
//        $this->_redisInstance->flushDB();//清空数据库
        $value = $this->getValue($pid);

        $reids = $this->_redisInstance->hgetall(self::REDIS_NAME);

        if (isset($reids)) {//判断哈希存在
            if ($this->_redisInstance->hexists(self::REDIS_NAME, $_SESSION['UId'])) { //判断哈希中此用户ID的field存在
                $userRedis = $this->_redisInstance->hget(self::REDIS_NAME, $_SESSION['UId']);
                $userRedis = json_decode($userRedis, TRUE);

                foreach ($value as $key => $values) {

                    if (array_key_exists($key, $userRedis)) {

                        if ($key == 'PBrand') {
                            $brand = key($values);
                            if (array_key_exists($brand, $userRedis['PBrand'])) {
                                $userRedis['PBrand'][$brand] += 1;
                                $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], json_encode($userRedis));
                            } 
                            else {
                                $userRedis['PBrand'][$brand] = 1;
                                $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], json_encode($userRedis));
                            }
                        } 
                        else if ($key == 'BCat') {
                            $brand = key($values);
                            if (array_key_exists($brand, $userRedis['BCat'])) {
                                $userRedis['BCat'][$brand] += 1;
                                $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], json_encode($userRedis));
                            } 
                            else {
                                $userRedis['BCat'][$brand] = 1;
                                $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], json_encode($userRedis));
                            }
                        } 
                        else if ($key == 'SCat') {
                            $brand = key($values);
                            if (array_key_exists($brand, $userRedis['SCat'])) {
                                $userRedis['SCat'][$brand] += 1;
                                $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], json_encode($userRedis));
                            } 
                            else {
                                $userRedis['SCat'][$brand] = 1;
                                $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], json_encode($userRedis));
                            }
                        } 
                        else {
                            $userRedis[$key] += 1;
                            $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], json_encode($userRedis));
                        }
                    } 
                    else {
                        $userRedis[$key] = $values;
                        $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], json_encode($userRedis));
                    }
                }
            } 
            else {
                $value = json_encode($value);
                $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], $value);
            }
        } 
        else {
            $value = json_encode($value);
            $this->_redisInstance->hset(self::REDIS_NAME, $_SESSION['UId'], $value);
        }
    }
    /**
     * 推送产品
     * @return type 
     */
    public function getPushInfo() {
//        $this->_redisInstance->flushDB();
        $redisValue = $this->getRedisUser();
        if (empty( $redisValue )) {
            $this->getCookieInfo();
        }
        else {
        $redisValue = $redisValue[$_SESSION['UId']];
        $redisValue = json_decode($redisValue,TRUE);
        
        $field = 'DISTINCT p1.PId';
        $table = 'product_levels p1,product_levels p2,product_levels p3';
        $table1 = 'product_age p1,product_age p2,product_age p3';
        $table2 = 'product_sex p1,product_sex p2';

        $wherelevels = 'p1.PId = p2.PId and p2.PId = p3.PId ';
        $whereage = 'p1.PId = p2.PId and p2.PId = p3.PId  ';
        $wheresex = 'p1.PId = p2.PId ';

        if ( array_key_exists('DHihgLevels', $redisValue) ) {
            $wherelevels .= 'and p1.DId = 3  ';
        }
        if ( array_key_exists('DMiddleLevels', $redisValue) ) {
            $wherelevels .= 'and p2.DId = 4 ';
        }
        if ( array_key_exists('DLowLevels', $redisValue) ) {
            $wherelevels .= 'and p3.DId = 5 ';
        }

        if ( array_key_exists('DOldAge', $redisValue) ) {
            $whereage .= 'and p1.DId = 6 ';
        }
        if ( array_key_exists('DYouthAge', $redisValue) ) {
            $whereage .= 'and p2.DId = 7 ';
        }
        if ( array_key_exists('DInfancyAge', $redisValue) ) {
            $whereage .= 'and p3.DId = 8 ';
        }

        if ( array_key_exists('DManSex', $redisValue) ) {
            $wheresex .= 'and p1.DId = 1 ';
        }
        if ( array_key_exists('DWomanSex', $redisValue) ) {
            $wheresex .= 'and p2.DId = 2';
        }

        $levelsId = Product_Levels::getInstance()->getLevelsProduct($field, $table, $wherelevels);

        $ageId = Product_Age::getInstance()->getAgeProduct($field, $table1, $whereage);

        $sexId = Product_Sex::getInstance()->getSexProduct($field, $table2, $wheresex);

        if ($levelsId) {
            foreach ($levelsId as $value) {
                $this->_redisInstance->sadd('levelsId', $value['PId']);
            }
        }
        if ($ageId) {
            foreach ($ageId as $value) {
                $this->_redisInstance->sadd('ageId', $value['PId']);
            }
        }
        if ($sexId) {
            foreach ($sexId as $value) {
                $this->_redisInstance->sadd('sexId', $value['PId']);
            }
        }

        foreach ($redisValue as $key => $value) {
            if ( $key == 'PBrand' ) {
                $cbrand = $value;
                natsort($cbrand);
                $con = count($cbrand);
                $last = array_slice($cbrand, $con - 1, $con, TRUE);
                $brankey = key($last);
                $productBrand = Product_Info::getInstance()->getProductInfoByBrand($brankey);
                if (isset($productBrand)) {
                    foreach ($productBrand as $value) {
                        $this->_redisInstance->sadd('productBrand', $value['PId']);
                    }
                }
            } 
            else if ($key == 'BCat') {
                $cbrand = $value;
                natsort($cbrand);
                $con = count($cbrand);
                $last = array_slice($cbrand, $con - 1, $con, TRUE);
                $brankey = key($last);
                $productBCat = Product_Info::getInstance()->getProductInfoByCat($brankey);
                if (isset($productBCat)) {
                    foreach ($productBCat as $value) {
                        $this->_redisInstance->sadd('productBCat', $value['PId']);
                    }
                }
            } else if ($key == 'SCat') {
                $cbrand = $value;
                natsort($cbrand);
                $con = count($cbrand);
                $last = array_slice($cbrand, $con - 1, $con, TRUE);
                $brankey = key($last);
                $productSCat = Product_Info::getInstance()->getProductInfoByCat($brankey);
                if (isset($productSCat)) {
                    foreach ($productSCat as $value) {
                        $this->_redisInstance->sadd('productSCat', $value['PId']);
                    }
                }
            }
        }
        return ($this->_redisInstance->sinter('levelsId', 'ageId', 'sexId', 'productBrand', 'productBCat', 'productSCat'));
        }
    }
    
/**
 *  保存cookie
 * @param type $pid 
 * 
 */
    public function saveToCookie($pid) {
        $value = $this->getValue($pid);

        if (isset($_COOKIE['userLike'])) {
            $cookie = unserialize($_COOKIE['userLike']);
            foreach ($value as $key => $values) {
                if (array_key_exists($key, $cookie)) {
                    if ($key == 'PBrand') {
                        $brand = key($values);
                        $cbrand = $cookie['PBrand'];
                        if (array_key_exists($brand, $cbrand)) {
                            $cbrand[$brand] += 1;
                            $cookie['PBrand'] = $cbrand;
                            setcookie('userLike', serialize($cookie));
                        } else {
                            $cbrand[$brand] = 1;
                            $cookie['PBrand'] = $cbrand;
                            setcookie('userLike', serialize($cookie));
                        }
                    }
                    if ($key == 'BCat') {
                        $brand = key($values);
                        $cbrand = $cookie['BCat'];
                        if (array_key_exists($brand, $cbrand)) {
                            $cbrand[$brand] += 1;
                            $cookie['BCat'] = $cbrand;
                            setcookie('userLike', serialize($cookie));
                        } else {
                            $cbrand[$brand] = 1;
                            $cookie['BCat'] = $cbrand;
                            setcookie('userLike', serialize($cookie));
                        }
                    }
                    if ($key == 'SCat') {
                        $brand = key($values);
                        $cbrand = $cookie['SCat'];
                        if (array_key_exists($brand, $cbrand)) {
                            $cbrand[$brand] += 1;
                            $cookie['SCat'] = $cbrand;
                            setcookie('userLike', serialize($cookie));
                        } else {
                            $cbrand[$brand] = 1;
                            $cookie['SCat'] = $cbrand;
                            setcookie('userLike', serialize($cookie));
                        }
                    } else {
                        $cookie[$key] += $values;
                        setcookie('userLike', serialize($cookie));
                    }
                } else {
                    $cookie[$key] = $values;
                    setcookie('userLike', serialize($cookie));
                }
            }
        }
        else {
            $value = serialize($value);
            setcookie('userLike', $value);
        }
    }

    /*
     * 获取用户推送产品ID
     */

    public function getCookieInfo() {
        $cookie = $_COOKIE['userLike'];
        if (empty($cookie)){
            return '';
        }
        else {
        $cookie = unserialize($_COOKIE['userLike']);
        // print_r($cookie);echo '<br>';
      // $this->_redisInstance->flushDB();
        $field = 'DISTINCT p1.PId';
        $table = 'product_levels p1,product_levels p2,product_levels p3';
        $table1 = 'product_age p1,product_age p2,product_age p3';
        $table2 = 'product_sex p1,product_sex p2';

        $wherelevels = 'p1.PId = p2.PId and p2.PId = p3.PId ';
        $whereage = 'p1.PId = p2.PId and p2.PId = p3.PId  ';
        $wheresex = 'p1.PId = p2.PId ';

        if (isset($cookie['DHihgLevels'])) {
            $wherelevels .= 'and p1.DId = 3  ';
        }
        if (isset($cookie['DMiddleLevels'])) {
            $wherelevels .= 'and p2.DId = 4 ';
        }
        if (isset($cookie['DLowLevels'])) {
            $wherelevels .= 'and p3.DId = 5 ';
        }

        if (isset($cookie['DOldAge'])) {
            $whereage .= 'and p1.DId = 6 ';
        }
        if (isset($cookie['DYouthAge'])) {
            $whereage .= 'and p2.DId = 7 ';
        }
        if (isset($cookie['DInfancyAge'])) {
            $whereage .= 'and p3.DId = 8 ';
        }

        if (isset($cookie['DManSex'])) {
            $wheresex .= 'and p1.DId = 1 ';
        }
        if (isset($cookie['DWomanSex'])) {
            $wheresex .= 'and p2.DId = 2';
        }

        foreach ($cookie as $key => $value) {
            if ($key == 'PBrand') {
                $cbrand = $cookie['PBrand'];
                natsort($cbrand);
                $con = count($cbrand);
                $last = array_slice($cbrand, $con - 1, $con, TRUE);
                $brankey = key($last);
                $productBrand = Product_Info::getInstance()->getProductInfoByBrand($brankey);
            } else if ($key == 'BCat') {
                $cbrand = $cookie['BCat'];
                natsort($cbrand);
                $con = count($cbrand);
                $last = array_slice($cbrand, $con - 1, $con, TRUE);
                $brankey = key($last);
                $productBCat = Product_Info::getInstance()->getProductInfoByCat($brankey);
            } else if ($key == 'SCat') {
                $cbrand = $cookie['SCat'];
                natsort($cbrand);
                $con = count($cbrand);
                $last = array_slice($cbrand, $con - 1, $con, TRUE);
                $brankey = key($last);
                $productSCat = Product_Info::getInstance()->getProductInfoByCat($brankey);
            }
        }

        $levelsId = Product_Levels::getInstance()->getLeveLsProduct($field, $table, $wherelevels);

        $ageId = Product_Age::getInstance()->getAgeProduct($field, $table1, $whereage);

        $sexId = Product_Sex::getInstance()->getSexProduct($field, $table2, $wheresex);
        
//        
//        echo '开始：';
//
//        print_r( $levelsId );
//        echo "<br/>";
//        print_r($ageId );
//        echo "<br/>";
//        print_r($sexId );
//        echo "<br/>";
//         print_r($productBrand );
//        echo "<br/>";
//         print_r($productBCat );
//        echo "<br/>";
//         print_r($productSCat );
//        echo "<br/>";
        /**
         * 返回产品PId
         */
        //产品
        $array = array_intersect(array_intersect($productBrand, $productBCat), $productSCat);
        
        $arrNew = array();
        foreach ($array as $key => $value) {
            $arrNew[] =  $value['PId'] ;
        }
        //维度
        $arr = array_intersect(array_intersect($levelsId, $ageId), $sexId);
        
        $resPId = array();
        foreach ($arr as $key => $value) {
            $resPId[] = $value['PId'];
        }
        
        $resultPId = array_intersect($arrNew, $resPId);
        //print_r( $resultPId );
        return $resultPId;
        }
    }

    /*
     * 获取用户redis
     */

    public function getRedisUser() {
//        $this->_redisInstance->flushDB();//清空数据库
        return $value = $this->_redisInstance->hgetall(self::REDIS_NAME);
    }

    public function __destruct() {
        
    }

}

?>